﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using CloudShot.Controls;
using CloudShot.Core.Interfaces;
using CloudShot.Core.Types;
using CloudShot.Properties;

namespace CloudShot.ImageStorages
{
  public class FileSystemStorage : IImageStorage
  {
    private readonly FileSystemStorageSettingsControl _settingsControl;
    private IConfigurationSection _configuration;

    public Image Logo
    {
      get { return Resources.folder; }
    }

    public string Name
    {
      get { return Resources.FileSystemStorage_Name; }
    }

    public string Description
    {
      get { return Resources.FileSystemStorage_Description; }
    }

    public IEnumerable<ImageSaveFormat> SupportedFormats
    {
      get
      {
        return new[]
        {
          ImageSaveFormat.Png,
          ImageSaveFormat.Jpg,
          ImageSaveFormat.Jpeg,
          ImageSaveFormat.Gif
        };
      }
    }

    public ISettingsControl SettingsControl
    {
      get { return _settingsControl; }
    }

    public FileSystemStorage()
    {
      _settingsControl = new FileSystemStorageSettingsControl(this);
    }

    public void Init(IConfigurationSection configuration)
    {
      _configuration = configuration;
      _settingsControl.Configuration = configuration;
    }

    public async Task<string> SaveImage(byte[] data, string shotName, bool isVideo)
    {
      return await SaveImageInternal(data, shotName);
    }

    private async Task<string> SaveImageInternal(byte[] data, string fullName)
    {
      var settings = _configuration.GetOrCreateAs<FileSystemSettings>();

      string folder = settings.FolderToSave;
      Directory.CreateDirectory(folder); //create directory if not exist

      string pathToSave = Path.Combine(folder, fullName);

      using (var fs = new FileStream(pathToSave, FileMode.Create))
      {
        await fs.WriteAsync(data, 0, data.Length);
      }

      if (settings.IsClickableLinksEnabled)
      {
        var uri = new Uri(pathToSave);
        pathToSave = uri.AbsoluteUri;
      }

      return pathToSave;
    }

    #region Settings

    public ImageSaveFormat CurrentImageFormat
    {
      get
      {
        var settings = _configuration.GetOrCreateAs<FileSystemSettings>();
        return settings.CurrentImageFormat;
      }
      internal set
      {
        var settings = _configuration.GetOrCreateAs<FileSystemSettings>();
        settings.CurrentImageFormat = value;
        _configuration.SaveAs(settings);
      }
    }

    #endregion
  }
}